import { create } from "zustand";
import { RTCPeerConnection, MediaStream } from "react-native-webrtc";
import {SignalMessageResponse} from "@/types/webrtc";

export interface WebRTCCallStateState {
    currentCall: SignalMessageResponse | null;
    peerConnection: RTCPeerConnection | null;
    localStream: MediaStream | null;
    remoteStream: MediaStream | null;
}

export interface WebRTCCallStateActions {
    setCurrentCall: (call: SignalMessageResponse | null) => void;
    setPeerConnection: (pc: RTCPeerConnection | null) => void;
    setLocalStream: (stream: MediaStream | null) => void;
    setRemoteStream: (stream: MediaStream | null) => void;
    reset: () => void;
}

export interface WebRTCCallStateStore {
    state: WebRTCCallStateState;
    actions: WebRTCCallStateActions;
}

const initialState: WebRTCCallStateState = {
    currentCall: null,
    peerConnection: null,
    localStream: null,
    remoteStream: null,
};

const WebRTCCallStore = create<WebRTCCallStateStore>((set, get) => ({
    state: { ...initialState },

    actions: {
        setCurrentCall: (call) =>
            set((store) => ({
                state: { ...store.state, currentCall: call },
            })),

        setPeerConnection: (pc) =>
            set((store) => ({
                state: { ...store.state, peerConnection: pc },
            })),

        setLocalStream: (stream) =>
            set((store) => ({
                state: { ...store.state, localStream: stream },
            })),

        setRemoteStream: (stream) =>
            set((store) => ({
                state: { ...store.state, remoteStream: stream },
            })),

        reset: () => {
            const { state } = get();

            // 主动释放资源
            state.peerConnection?.close();
            state.localStream?.getTracks().forEach((track) => track.stop());
            state.remoteStream?.getTracks().forEach((track) => track.stop());

            set(() => ({
                state: { ...initialState },
            }));
        },
    },
}));

export default WebRTCCallStore;
